﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;


namespace BadHabit.Factory.Controls {

    /// <summary>
    /// Base Class for TaskPanel and PostItPanel class.
    /// </summary>
    public class TaskPanelBase : GenericPanel {
       
        private Data.TaskDataSet dsTask;

        
        

        public TaskPanelBase() {
            Initialized += new EventHandler(TaskPanelBase_Initialized);
            Loaded += new RoutedEventHandler(TaskPanelBase_Loaded);
        }
                

        void TaskPanelBase_Initialized(object sender, EventArgs e) {
            AssignButtonEvents();            
        }



        public virtual void AddProjectTask_Executed(object sender, ExecutedRoutedEventArgs e) {
        }

        public virtual void AddTask_Executed(object sender, ExecutedRoutedEventArgs e) {
        }

        public Data.TaskDataSet.TaskDataTable TaskDataContext {
            get {
                return TasksContainer.DataContext as Data.TaskDataSet.TaskDataTable;
            }
        }
       
        /// <summary>
        /// Request the project data.
        /// </summary>
        /// <param name="selectedProject"></param>
        protected override bool RequestData() {

            // if no Project at the context return
            if (Project == null)
                return false;

            // read tasks            
            try {
                dsTask = new BadHabit.Factory.Data.TaskDataSet();
                dsTask.EnforceConstraints = false;
                dsTask.Merge(TasksFromWebSevices());
            } catch (Exception ex) {
                Windows.Error.ShowError(ex, Properties.Resources.COULD_NOT_READ_TASKS);
                return false;
            }
            
            TasksContainer.DataContext = dsTask.Task;
                        
            // shows only the backlog item of the selected sprint                 
            BacklogItemListBox.BacklogItemFilter = GetAffectedBacklogItem(dsTask.Task);
            BacklogItemListBox.SprintNumberFilter = TaskToolBar.SprintNumberFilter;            

            BacklogItemListBox.RefreshFilter();            

            return true;
        }


    
        /// <summary>
        /// Computes the distinct backlog item numbers on the task table
        /// and sets the AffectedBacklogItemNumbers property.
        /// </summary>
        /// <param name="tasks">The task table.</param>
        private BacklogItemListBox.VisibleBacklogItemIdentity[] GetAffectedBacklogItem(Data.TaskDataSet.TaskDataTable tasks) {
            List<BacklogItemListBox.VisibleBacklogItemIdentity> itemsList = new List<BacklogItemListBox.VisibleBacklogItemIdentity>();


            foreach (Data.TaskDataSet.TaskRow task in tasks) {

                BacklogItemListBox.VisibleBacklogItemIdentity id = new BacklogItemListBox.VisibleBacklogItemIdentity();

                id.BacklogItemUId = task.BacklogItemUId;
                id.SprintUId = task.SprintUId;

                if (!itemsList.Contains(id)) 
                    itemsList.Add(id);
            }

            return itemsList.ToArray();
        }
        

        /// <summary>
        /// Call the correct webservice acording the task filter selection.
        /// </summary>
        /// <returns></returns>
        private System.Data.DataSet TasksFromWebSevices() {

            // Daily tasks
            if (TaskToolBar.SprintNumberFilter == 0)
                return Client.Service.RetriveProjectDaillyTasks(Project.ProjectUId);
            
            // All tasks
            if(TaskToolBar.IsAllSprintSelected)
                return Client.Service.RetriveProjectTasks(Project.ProjectUId, -1);

            // sprint tasks
            return Client.Service.RetriveProjectTasks(Project.ProjectUId, (short)TaskToolBar.SprintNumberFilter);                
             
        }

        /// <summary>
        /// Gets the backlog item listbox.
        /// </summary>
        private BadHabit.Factory.Controls.BacklogItemListBox BacklogItemListBox {
            get {
                return (BadHabit.Factory.Controls.BacklogItemListBox) FindName("backlogItemListBox");
            }
        }

        /// <summary>
        /// Gets the task container.
        /// </summary>
        private ContentControl TasksContainer {
            get {
                return (ContentControl)FindName("taskContainer");
            }
        }

        public virtual bool IsAddingNewOrEditing {
            get {
                return false;
            }
        }

        /// <summary>
        /// Gets the task container.
        /// </summary>
        public TaskToolBar TaskToolBar {
            get {
                return (TaskToolBar)FindName("taskToolBar");
            }
        }


        private System.Data.DataRowView oldBacklogItemFilter;
        private string oldSearchFilter;
        public void SuspendFilter(bool maintainSelectedItem) {
            if (!maintainSelectedItem)
                oldBacklogItemFilter = null;
            else
                oldBacklogItemFilter = BacklogItemListBox.SelectedBacklogItem;
            oldSearchFilter = TaskToolBar.searchTextBox.Text;
            TaskToolBar.searchTextBox.Text = "";
        }

        

        public void ResumeFilter() {
            TaskToolBar.searchTextBox.Text = oldSearchFilter;                        
            BacklogItemListBox.SelectedBacklogItem = oldBacklogItemFilter;
            
        }
        


        /// <summary>
        /// Changes to another task view.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ChangeView_Click(object sender, RoutedEventArgs e) {

            // alert for lost changes
            if (!CanLostChanges(null, null))
                return;

            Client.FactoryMainWindow.ChangeTaskTabView();
        }


        /// <summary>
        /// Assign the toolbar events to the panel.
        /// </summary>
        protected void AssignButtonEvents() {
           
            TaskToolBar.taskFilterComboBox.SelectionChanged += new SelectionChangedEventHandler(taskFilterComboBox_SelectionChanged);
            
            

            TaskToolBar.tableViewButton.Click += new RoutedEventHandler(ChangeView_Click);

            TaskToolBar.postItViewButton.Click += new RoutedEventHandler(ChangeView_Click);


           
            
        }

        protected string[] GetTasksFromClipBoard() {
            if (!Clipboard.ContainsText())
                return null;

            string text = Clipboard.GetText().Replace("\r", "");

            return text.Split(new string[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);   

        }

     

        /// <summary>
        /// When the task filter changes, request tasks.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void taskFilterComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {

            // if this change was triggerd by a cancel, get out
            if(sender.Equals(CancelChangeControlSender))
                return;

            // alert for lost changes
            if (e.RemovedItems.Count > 0 && !CanLostChanges(sender, e.RemovedItems[0])) {                
                return;
            }

            // bind the tasks for the proper filter
            CallRequestData();
        }



        private void TaskPanelBase_Loaded(object sender, RoutedEventArgs e) {

            if (Client.FactoryMainWindow.IsBacklogDirty) {
                Windows.Error.ShowAlert("Items have been added or removed from the backlog.\nYou should commit your changes first in order to add tasks.");
                this.IsEnabled = false;
            } else
                this.IsEnabled = true;
        }


        internal static void OpenTaskTailWindow(Data.TaskDataSet.TaskRow task) {
            if (task == null)
                return;
            Client.FactoryMainWindow.tabControl.tailTabItem.IsSelected = true;
            Client.FactoryMainWindow.tabControl.tailPanel.TaskFilter = task;
            

        }

      

        internal static void MoveTask(Data.TaskDataSet.TaskRow task, string sprintUId, string backlogitemUId, short backlogItemNumber, bool promptConfirmation) {
            if (promptConfirmation) {
                MessageBoxResult d = Windows.Error.ShowDialog(
                    String.Format(Properties.Resources.Move_task_to_item, task.TaskName, backlogItemNumber), Properties.Resources.Move_Task, MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No);
                if (d == MessageBoxResult.No)
                    return;
            }

            task.SprintUId = sprintUId;
            task.BacklogItemUId = backlogitemUId;
            task.BacklogItemNumber = backlogItemNumber;
        }
            
       

    }
}
